package com.qianfeng.exam.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.exam.pojo.Categories;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class BeanConfig {//声明是一个配置类,取代 xml 最外面的<beans 标签

    /**
     * <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
     * <property name=""
     * </bean>
     *
     * @return
     */
    @Bean //配置阿里巴巴的德鲁伊连接池(数据源)
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql:///exam?useUnicode=true&characterEncoding=UTF-8&useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("1234");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        return dataSource;
    }

    @Bean //事务管理器,依赖dataSource,借以获得连接,进而控制事务逻辑
    public DataSourceTransactionManager transactionManager(DruidDataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

    @Bean //配置会话工厂 依赖dataSource数据源
    public SqlSessionFactoryBean sqlSessionFactoryBean(DruidDataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        //配置mybatis映射文件所在目录位置
        ClassPathResource classPathResource = new ClassPathResource("mybatis/mybatis.xml");
        sqlSessionFactoryBean.setConfigLocation(classPathResource);
        return sqlSessionFactoryBean;
    }

    @Bean //扫描 mapper 接口并创建代理对象
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.qiangfeng.exam.mapper");
        return mapperScannerConfigurer;
    }
    @Bean // jackson的objectMapper对象,我们没有自己new,而是让spring工厂帮我们通过反射创建出来这个对象,这就是控制反转,提高的代码的可维护行,降低了耦合度,方便了了多组之间的协同合作
    public ObjectMapper objectMapper(){
        return new ObjectMapper();
    }
    @Bean // 编码格式对象
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean // 编码格式对象
    public Categories categories() {
        return new Categories();
    }

}
